package com.yida.gwj.oracle.basic.controller;

import com.mybatisflex.core.query.QueryWrapper;
import com.yida.common.core.text.Convert;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.core.web.domain.AjaxResult;
import com.yida.gwj.oracle.basic.domain.House;
import com.yida.gwj.oracle.basic.domain.TjSyqZftj;
import com.yida.gwj.oracle.basic.domain.Zrz;
import com.yida.gwj.oracle.basic.domain.dto.*;
import com.yida.gwj.oracle.basic.domain.request.GwjInitApiRequest;
import com.yida.gwj.oracle.basic.service.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.yida.gwj.oracle.basic.domain.table.CyqyxxTableDef.CYQYXX;
import static com.yida.gwj.oracle.basic.domain.table.HouseTableDef.HOUSE;
import static com.yida.gwj.oracle.basic.domain.table.KfxmTableDef.KFXM;
import static com.yida.gwj.oracle.basic.domain.table.TjSyqZftjTableDef.TJ_SYQ_ZFTJ;
import static com.yida.gwj.oracle.basic.domain.table.ZrzTableDef.ZRZ;

/**
 * @author ml
 * @create 2018-01-05--14:12
 */
@RestController
@RequestMapping("/api")
public class GwjApiController {
    @Resource
    private ITjSyqZftjService tjSyqZftjService;

    @Resource
    private IHouseService houseService;

    @Resource
    private IZrzService zrzService;

    @Resource
    private IKfxmService kfxmService;

    @Resource
    private IAlQlrNewService alQlrNewService;

    @GetMapping("/getCommunity")
    public AjaxResult getCommunity(GwjInitApiRequest request) {
        QueryWrapper wrapper = QueryWrapper.create().select().select(KFXM.X_M_B_S_M, KFXM.X_M_M_C, KFXM.X_M_D_Z, CYQYXX.Q_Y_M_C)
                .from(KFXM)
                .leftJoin(CYQYXX).on(KFXM.K_F_Q_Y_B_S_M.eq(CYQYXX.Q_Y_B_S_M))
                .where(KFXM.S_F_Y_X.eq(1))
                .and(KFXM.X_M_M_C.like(request.getProjectName()))
                .and(CYQYXX.Q_Y_M_C.like(request.getCompanyName()))
                .orderBy(KFXM.X_M_B_S_M.desc());
        List<KfxmDTO> kfxms = kfxmService.listAs(wrapper, KfxmDTO.class);
        List<GwjInitApiProjectDTO> dtos = new ArrayList<>();
        if (!kfxms.isEmpty()) {
            kfxms.forEach(k -> {
                GwjInitApiProjectDTO dto = new GwjInitApiProjectDTO();
                dto.setProjectName(Convert.toStr(k.getXMMC(), ""));
                dto.setProjectCode(Convert.toLong(k.getXMBSM()));
                dto.setCompanyName(Convert.toStr(k.getQYMC(), ""));
                dto.setAddress(Convert.toStr(k.getXMDZ(), ""));
                dtos.add(dto);
            });
        }
        return AjaxResult.success(dtos);
    }

    @GetMapping("/getBuild")
    public AjaxResult getBuild(GwjInitApiRequest request) {
        List<Zrz> zrzs = zrzService.list(QueryWrapper.create().where(ZRZ.X_M_B_S_M.eq(request.getProjectCode()))
                .and(ZRZ.S_F_Y_X.eq(1))
                .and(ZRZ.Z_R_Z_B_S_M.in(Arrays.asList(request.getBuildCode().split(","))))
                .orderBy(ZRZ.Z_R_Z_H.asc()));
        if (!zrzs.isEmpty()) {
            zrzs.forEach(zrz -> {
                zrz.setTotalOwner(houseService.getCount(1, zrz.getZRZBSM()));
                zrz.setResidence(houseService.getCount(1, zrz.getZRZBSM(), "别墅,住宅"));
            });
        }
        List<GwjInitApiBuildDTO> dtos = new ArrayList<>();
        if (!zrzs.isEmpty()) {
            zrzs.forEach(o -> {
                GwjInitApiBuildDTO dto = new GwjInitApiBuildDTO();
                dto.setDoorplate(Convert.toStr(o.getMPH(), ""));
                dto.setBuildRealName(Convert.toStr(o.getJZWMC(), ""));
                dto.setProjectCode(Convert.toLong(o.getXMBSM()));
                dto.setBuildCode(Convert.toLong(o.getZRZBSM()));
                dto.setTotalOwner(Convert.toInt(o.getTotalOwner()));
                dto.setResidence(Convert.toInt(o.getResidence()));
                dto.setTotalLayer(Convert.toInt(o.getZCS()));
                dto.setBuildNo(Convert.toStr(o.getZRZH(), ""));
                dto.setTotalSize(Convert.toBigDecimal(o.getSCJZMJ(), BigDecimal.ZERO));
                dto.setPeriodSize(Convert.toBigDecimal(o.getQFJZMJ(), BigDecimal.ZERO));
                dtos.add(dto);
            });
        }
        return AjaxResult.success(dtos);
    }

    @GetMapping("/getHouse")
    public AjaxResult getHouse(GwjInitApiRequest request) {
        List<House> houses = houseService.list(QueryWrapper.create().where(HOUSE.S_F_Y_X.eq(1))
                .and(HOUSE.Z_R_Z_B_S_M.in(Arrays.asList(request.getBuildCode().split(","))))
                .orderBy(HOUSE.H_B_S_M.asc()));
        List<GwjInitApiHouseDTO> dtos = new ArrayList<>();
        if (!houses.isEmpty()) {
            houses.forEach(h -> {
                GwjInitApiHouseDTO dto = new GwjInitApiHouseDTO();
                dto.setBuildFramework(Convert.toStr(h.getJZJG(), ""));
                dto.setUseType(Convert.toStr(h.getGHYT(), ""));
                dto.setNominalLayer(Convert.toStr(h.getMYC(), ""));
                dto.setBuildCode(Convert.toLong(h.getZRZBSM()));
                dto.setHouseCode(Convert.toLong(h.getHBSM()));
                dto.setHouseLocation(Convert.toStr(h.getFWZL(), ""));
                dto.setFloorNum(Convert.toStr(h.getSJC(), ""));
                dto.setRoomNum(Convert.toStr(h.getHH(), ""));
                dto.setHouseholdNum(Convert.toStr(h.getSHWZ(), ""));
                dto.setDoorModel(Convert.toStr(h.getHX(), ""));
                dto.setActualSize(Convert.toBigDecimal(h.getXFJZMJ(), new BigDecimal("0.00")));
                dto.setInnerActualSize(Convert.toBigDecimal(h.getXFTNJZMJ(), new BigDecimal("0.00")));
                dto.setForecastSize(Convert.toBigDecimal(h.getQFYCJZMJ(), new BigDecimal("0.00")));
                dto.setInnerForecastSize(Convert.toBigDecimal(h.getQFTNJZMJ(), new BigDecimal("0.00")));
                dto.setRestrictRegisterFlag(Convert.toStr(h.getIS_RESTRICT_REGISTER()));
                dto.setMortRegisterFlag(Convert.toStr(h.getIS_MORT_REGISTER()));
                dto.setTransferRegisterFlag(Convert.toStr(h.getIS_TRANSFER_REGISTER()));
                dto.setInitialRegisterFlag(Convert.toStr(h.getIS_INITIAL_REGISTER()));
                dto.setHousePredictMortRegisterFlag(Convert.toStr(h.getIS_HOUSE_PREDICT_MORT_REGISTER()));
                dto.setHousePredictRegisterFlag(Convert.toStr(h.getIS_HOUSE_PREDICT_REGISTER()));
                dto.setHouseContractRegisterFlag(Convert.toStr(h.getIS_HOUSE_CONTRACT_REGISTER()));
                dto.setContractSignFlag(Convert.toStr(h.getIS_CONTRACT_SIGN()));
                dto.setSubscribeFlag(Convert.toStr(h.getIS_SUBSCRIBE()));
                dto.setSalePermitFlag(Convert.toStr(h.getIS_SALE_PERMIT()));
                dto.setHousingPrice(Convert.toBigDecimal(h.getBARGAINVALUE(), new BigDecimal("0.00")));
                dtos.add(dto);
            });
        }
        return AjaxResult.success(dtos);

    }

    @GetMapping("/getOwner")
    public AjaxResult getOwner(GwjInitApiRequest request) {
        List<TjSyqZftj> tjSyqZftjs = tjSyqZftjService.list(QueryWrapper.create().where(TJ_SYQ_ZFTJ.H_B_S_M.in(Arrays.asList(request.getHouseCode().split(",")))));
        List<GwjInitApiOwnerDTO> dtos = new ArrayList<>();
        if (!tjSyqZftjs.isEmpty()) {
            tjSyqZftjs.forEach(o -> {
                GwjInitApiOwnerDTO dto = new GwjInitApiOwnerDTO();
                dto.setHouseCode(Convert.toLong(o.getHBSM()));
                dto.setOwnerName(Convert.toStr(o.getQLR(), ""));
                dto.setCardNum(Convert.toStr(o.getSFZMH(), ""));
                dtos.add(dto);
            });
            dtos.forEach(owner -> {
                if (StringUtils.isNotBlank(owner.getCardNum())) {
                    owner.setOwnerPhone(getOwnerPhone(owner.getCardNum().split(",")));
                }
            });
        }
        return AjaxResult.success();
    }

    public String getOwnerPhone(String[] cardNums) {
        String phone = alQlrNewService.getPhone(cardNums);
        if (StringUtils.isBlank(phone)) {
            return phone;
        }
        //处理空格和特殊符号替换为,
        String pattern = "[!|@|#|$|%|^|&|*|(|)|_|+|=|{|}|:|\"|<|>|?|\\[|\\]|;|'|.|/|！|@|#|￥|%|…|…|&|*|（|）|+|：|“|《|》|？|=|【|】|；|‘|，|。|、|’|`|~|·]";
        phone = phone.replaceAll("\\s{2,}", ",").replaceAll(pattern, ",");
        //转出数组并去重
        String[] phoneArr = Convert.toStrArray(phone.trim());
        List<String> phones = Arrays.stream(phoneArr).filter(p -> StringUtils.isNotBlank(p)).distinct().collect(Collectors.toList());
        return StringUtils.join(phones, ",");
    }
}
